<template>
    <!-- 头部信息 -->
    <HeaderView title="购物车" :hasBack='false' path=""/>

    <!-- 内容部分 -->
    <div class="content">
        <div class="item" v-for="item in list as any" :key="item.id">
          <van-swipe-cell>
            <div class="itemBox">
              <div class="itemLeft">
                <van-checkbox-group v-model="checked">
                  <van-checkbox :name="item.id" @click="danxuanRadio"></van-checkbox>
                </van-checkbox-group>

                <div class="img"><img :src="item.goods.cover_url"/></div>
                <div class="desc">
                    <p class="title">{{item.goods.title}}</p>
                    <p>￥{{item.goods.price}}</p>
                </div>
              </div>

              <div class="itemRight">
                <p class="stock">库存: {{item.goods.stock === 0 ? 0 : item.goods.stock - item.num}}</p>
                <div class="stepper">
                  <van-stepper v-model="item.num" :min="1" :max="item.goods.stock" :name="item.id" @change="numChange"/>
                </div>
              </div>
            </div>

            <template #right>
              <van-button square type="danger" text="删除" class="delete-button" @click="deleteGoods(item.id)"/>
            </template>
          </van-swipe-cell>
        </div>
    </div>

    <!-- 结算按钮 -->
    <div class="pay">
      <van-checkbox v-model="checkAll" @click="allCheck"></van-checkbox>
      <p class="allPay">
        <span class="price">￥{{totalPrice}}</span>
        <van-button type="danger" size="small">结算</van-button>
      </p>
    </div>

    <!-- 底部tabbar -->
    <BottomView/>

    <!-- 时间超时 -->
    <TimeOutView v-if="timeFlag"/>
</template>

<script lang="ts" setup>
import HeaderView from '@/components/Header/IndexView.vue'
import TimeOutView from '@/components/TimeOut/IndexView.vue'
import BottomView from '@/components/Bottom/IndexView.vue'

import { ref, onActivated, onMounted, computed, nextTick } from 'vue'
import { showToast } from 'vant'
import { GetList, CheckedCart, UndateNum, DeleteProduct } from '@/api/shopcart'
import { ShopcartNum } from '@/pinia'
import { storeToRefs } from 'pinia'

const { saveNum } = ShopcartNum()
const store = ShopcartNum()
const { shopcartNum } = storeToRefs(store)
const timeFlag = ref(false) // 请求超时 显示界面
const list = ref([]) // 购物车产品
const checked = ref<any>([]) // radio选中集合
const checkAll = ref(false) // 全选
const listNum = ref(0)

// 数据初始化
const init = async () => {
  const res = await GetList('include=goods').catch(err => {
    if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') timeFlag.value = true
  })

  try {
    if (res?.status === 200) {
      list.value = res.data.data
      saveNum(res.data.data.length)
      listNum.value = res.data.data.length
      nextTick(() => {
        // is_checked === 1就选中产品
        checked.value = list.value.filter((item: {is_checked: number}) => item.is_checked === 1).map((itemB: {id: number}) => itemB.id)
        if (checked.value.length === list.value.length) {
          checkAll.value = true
        }
      })
    }
  } catch (error) {
    console.log(error)
  }
}
onMounted(() => { init() })

// 计算总价
const totalPrice = computed(() => {
  let sum = 0
  list.value.filter((item: {id: number}) => checked.value.includes(item.id)).forEach((itemB: {num: string, goods: {price: string}}) => {
    sum += parseInt(itemB.num) * parseInt(itemB.goods.price)
  })
  return sum
})

// 点击单选
const danxuanRadio = async () => {
  if (checked.value.length === list.value.length) {
    checkAll.value = true
  } else {
    checkAll.value = false
  }

  await CheckedCart({ cart_ids: checked.value }).catch(err => {
    if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') {
      showToast({ type: 'fail', message: '请稍后再试', duration: 1500, forbidClick: true })
    }
  })
}

// 点击全选
const allCheck = () => {
  if (checkAll.value) { // 全选
    checked.value = list.value.map((item: {id: number}) => item.id)
    CheckedCart({ cart_ids: checked.value })
  } else { // 全不选
    checked.value = []
    CheckedCart({ cart_ids: [] })
  }
}

// 改变数量
const numChange = async (value: string, detail: { name: string }) => {
  await UndateNum(detail.name, { num: value }).catch(err => {
    if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') {
      showToast({ type: 'fail', message: '请稍后再试', duration: 1500, forbidClick: true })
    }
  })
}

// 删除产品
const deleteGoods = async (id: number) => {
  const res = await DeleteProduct(id).catch(err => {
    if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') {
      showToast({ type: 'fail', message: '请稍后再试', duration: 1500, forbidClick: true })
    }
  })

  try {
    if (res?.status === 204) {
      showToast({
        type: 'success',
        message: '删除成功',
        forbidClick: true,
        onClose: () => {
          init()
        }
      })
    }
  } catch (error) {
    console.log(error)
  }
}

onActivated(() => {
  if (list.value.length !== shopcartNum.value) {
    init()
  }
})

</script>

<script lang="ts">
export default {
  name: 'shopcartView'
}
</script>

<style lang="scss" scoped>
  .content{
    width: 96%;
    position: fixed;
    top: 50px;
    left: 2%;
    right: 2%;
    bottom: 90px;
    overflow: hidden;
    overflow-y: scroll;
    .delete-button{
      height: 100%;
    }
    .itemBox{
      display: flex;
      justify-content: space-between;
      font-size: 14px;
      margin-top: 20px;
      .itemLeft{
        display: flex;
        justify-content: space-around;
        .van-checkbox-group{
           align-self: center;
           margin-right: 5px;
        }
        .img{
          width: 80px;
          height: 80px;
          border: 1px solid #ccc;
        }
        .desc{
          margin-top: 12px;
          .title{
            margin-bottom: 8px;
          }
        }
      }
      .itemRight{
        margin-top: 12px;
        .stock{
          text-align: right;
          margin-bottom: 16px;
        }
      }
    }
  }

  .pay{
    width: 96%;
    padding: 0 2%;
    position: fixed;
    left: 0;
    bottom: 50px;
    display: flex;
    justify-content: space-between;
    .van-checkbox{
       font-size: 14px;
    }
    .allPay{
      font-size: 16px;
      display: flex;
      .price{
        align-self: center;
        margin-right: 8px;
      }
    }
  }
</style>
